<?php

namespace App\Http\Middleware;

use App\Jobs\LoggingOperationLog;
use App\Models\Common\Constant;
use Closure;
use Illuminate\Http\Request;

class OperationLog
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if ($controller = $request->route()->getController()) {
            if ($controller->needLogging) {
                $controllerName = $controller->name;
                $admin = $controller->admin;
                $logContent = strval($controller->logContent);

                if ($controllerName && $logContent && $admin) {
                    if (mb_strlen($logContent) >= 80) { // varchar255最多85个汉字
                        $logContent = mb_substr($logContent, 0, 80) . '...';
                    }
                    $parkingLotID = $controller->parkingLotID;
                    $loginIp = getRealClientIp();
                    $keyword = $controller->keyword;

                    LoggingOperationLog::dispatch($admin, $controllerName, $logContent, $loginIp, $parkingLotID, $keyword)->onQueue(Constant::QUEUE_DEFAULT);
                }
            }
        }
        return $response;
    }
}
